package com.xintonghua.bussiness.ui.user.manage;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.xintonghua.base.widget.MyItemTextView;
import com.xintonghua.bussiness.R;
import com.xintonghua.bussiness.base.BaseActivity;
import com.xintonghua.bussiness.bean.StaffBean;
import com.xintonghua.bussiness.event.EmployeeRefreshEvenBus;
import com.xintonghua.bussiness.util.GlideUtils;
import com.xintonghua.bussiness.util.ImageTools;
import com.xintonghua.bussiness.util.ImageUtils;
import com.xintonghua.bussiness.util.MyState;
import com.xintonghua.bussiness.util.MyUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.addapp.pickers.listeners.OnItemPickListener;
import cn.addapp.pickers.picker.SinglePicker;
import me.iwf.photopicker.PhotoPicker;

/**
 * 作者：wanxianyi
 * 时间：2018/3/9.
 * 包名：com.xintonghua.bussiness.ui.user.manage
 */

public class AddEmployeeActivty extends BaseActivity {
    @BindView(R.id.edt_qq)
    EditText edtQq;
    @BindView(R.id.utils_sex)
    MyItemTextView utilsSex;
    @BindView(R.id.utils_position)
    MyItemTextView utilsPosition;
    @BindView(R.id.edt_phone)
    EditText edtPhone;
    @BindView(R.id.edt_password)
    EditText edtPassword;
    @BindView(R.id.tv_sure_add_employee)
    TextView tvSureAddEmployee;
    @BindView(R.id.add_employee_head)
    LinearLayout addEmployeeHead;
    @BindView(R.id.iv_employee_head)
    ImageView ivEmployeeHead;
    @BindView(R.id.edt_note)
    EditText edtNote;
    private int positionId = 0;
    private int sex = 0;
    private List<String> pList = new ArrayList<>();
    private String imagePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_employee);
        EventBus.getDefault().register(this);
        ButterKnife.bind(this);
        onSimpleActionBar();
        setSimpleActionBar("添加员工");
        pList.add("男");
        pList.add("女");
    }

    @OnClick({R.id.utils_sex, R.id.utils_position, R.id.tv_sure_add_employee, R.id.add_employee_head})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.utils_sex:
                showSex();
                break;
            case R.id.utils_position:
                openActivity(PositionActivity.class);
                break;
            case R.id.tv_sure_add_employee:
                if (TextUtils.isEmpty(imagePath)) {
                    mToast("请选择头像");
                    return;
                }
                if (TextUtils.isEmpty(getStr(edtQq))) {
                    mToast("请输入名字");
                    return;
                }
                if (TextUtils.isEmpty(utilsSex.getMsg())) {
                    mToast("请选择性别");
                    return;
                }
                if (TextUtils.isEmpty(utilsPosition.getMsg())) {
                    mToast("请选择职位");
                    return;
                }
                if (TextUtils.isEmpty(getStr(edtPhone))) {
                    mToast("请输入联系方式");
                    return;
                }
                if (getStr(edtPhone).length() != 11) {
                    mToast("请输入正确的联系方式");
                    return;
                }
                if (TextUtils.isEmpty(getStr(edtPassword))) {
                    mToast("请输入密码");
                    return;
                }
                httpCent.addStaff(imagePath, getStr(edtQq), sex, positionId, getStr(edtPhone), getStr(edtPassword), getStr(edtNote), this, MyState.requestTwo);
                break;
            case R.id.add_employee_head:
                MyUtils.startPhotoPicker(this, 1, 100);
                break;
        }
    }

    @Override
    public void dataBack(Object data, int order) {
        super.dataBack(data, order);
        switch (order) {
            case MyState.requestOne:
                imagePath = (String) data;
                GlideUtils.load(this, ivEmployeeHead, imagePath);
                break;
            case MyState.requestTwo:
                mToast("添加成功！");
                EventBus.getDefault().post(new EmployeeRefreshEvenBus());
                finish();
                break;
        }
    }

    /**
     * 选择性别
     */
    private void showSex() {

        SinglePicker<String> picker = new SinglePicker<>(this, pList);
        picker.setCanLoop(false);//不禁用循环
        picker.setLineVisible(true);
        picker.setShadowVisible(true);
        picker.setTextSize(18);
        picker.setSelectedIndex(1);
        picker.setWheelModeEnable(true);
        picker.setLabel(null);
        picker.setWeightEnable(true);
        picker.setWeightWidth(1);
        picker.setSelectedTextColor(ContextCompat.getColor(this, R.color.red));//前四位值是透明度
        picker.setUnSelectedTextColor(ContextCompat.getColor(this, R.color.grey));
        picker.setOnItemPickListener(new OnItemPickListener<String>() {
            @Override
            public void onItemPicked(int index, String item) {
                if (pList.get(index).equals("男")) {
                    sex = 1;
                } else {
                    sex = 0;
                }
                if (sex == 0) {
                    utilsSex.setMsg("女");
                } else {
                    utilsSex.setMsg("男");
                }
            }
        });
        picker.show();
    }

    /**
     * 选择职位
     *
     * @param bean
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(StaffBean bean) {
        utilsPosition.setMsg(bean.getName());
        positionId = bean.getId();
    }


    File cropImagePaths;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 100:
                    if (data != null) {
                        ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                        if (photos != null) {
                            File file = new File(photos.get(0));
                            cropImagePaths = new File(MyUtils.getImagePath(), "IMG_" + System.currentTimeMillis() + ".jpg");
                            cropImageUriWithXY(Uri.fromFile(file), cropImagePaths, 1, 1, 200);
                        }
                    }
                    break;
                case 200:
                    ImageTools.loadImage(this, cropImagePaths.getPath(), this, MyState.requestOne);
                    break;
            }
        }
    }

    /**
     * 按比例裁剪图片
     *
     * @param uri
     * @param file
     * @param x
     * @param y
     * @param requestCode
     */
    protected void cropImageUriWithXY(Uri uri, File file, int x, int y, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", x);
        intent.putExtra("aspectY", y);
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
